import axios from 'axios';

const API_URL = 'http://localhost:8080/api/departments';

// 获取JWT令牌
const getAuthHeader = () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.token) {
        return { Authorization: `Bearer ${user.token}` };
    } else {
        return {};
    }
};

// 获取所有科室
const getAllDepartments = async () => {
    try {
        const response = await axios.get(API_URL, {
            headers: getAuthHeader()
        });
        return response.data;
    } catch (error) {
        console.error('Error fetching departments:', error);
        throw error;
    }
};

// 根据ID获取科室
const getDepartmentById = async (departmentId) => {
    try {
        const response = await axios.get(`${API_URL}/${departmentId}`, {
            headers: getAuthHeader()
        });
        return response.data;
    } catch (error) {
        throw error;
    }
};

// 创建科室
const createDepartment = async (departmentData) => {
    try {
        const response = await axios.post(API_URL, departmentData, {
            headers: {
                ...getAuthHeader(),
                'Content-Type': 'application/json'
            }
        });
        return response.data;
    } catch (error) {
        throw error;
    }
};

// 更新科室
const updateDepartment = async (departmentId, departmentData) => {
    try {
        const response = await axios.put(`${API_URL}/${departmentId}`, departmentData, {
            headers: {
                ...getAuthHeader(),
                'Content-Type': 'application/json'
            }
        });
        return response.data;
    } catch (error) {
        throw error;
    }
};

// 删除科室
const deleteDepartment = async (departmentId) => {
    try {
        await axios.delete(`${API_URL}/${departmentId}`, {
            headers: getAuthHeader()
        });
        return true;
    } catch (error) {
        throw error;
    }
};

const departmentService = {
    getAllDepartments,
    getDepartmentById,
    createDepartment,
    updateDepartment,
    deleteDepartment
};

export default departmentService; 